package com.pai4j.aigc.controller;

import com.pai4j.aigc.llm.entity.LLMModelEntity;
import com.pai4j.aigc.llm.service.LLMModelService;
import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.common.enums.ResponseCodeEnum;
import com.pai4j.domain.dto.llmconfig.LLMModelUpsertDTO;
import com.pai4j.domain.vo.response.UploadResultVO;
import com.pai4j.log.annotation.OperationLog;
import com.pai4j.remote.oss.FileServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/aigc/admin/llm/model")
public class LLMModelAdminController {

    @Autowired
    private LLMModelService modelService;

    @Autowired
    private FileServiceClient fileServiceClient;

    @PostMapping("/upsert")
    @OperationLog(module = "AIGC管理", operation = "LLM模型新增更新", description = "管理员创建或更新LLM模型配置", recordParams = false)
    public PAIResponseBean<LLMModelEntity> upsert(@RequestBody LLMModelUpsertDTO dto) {
        LLMModelEntity e = new LLMModelEntity();
        e.setId(dto.getId());
        e.setTenantId(dto.getTenantId());
        e.setCode(dto.getCode());
        e.setName(dto.getName());
        e.setProvider(dto.getProvider());
        e.setIconUrl(dto.getIconUrl());
        e.setBaseUrl(dto.getBaseUrl());
        e.setApiKey(dto.getApiKey());
        e.setModel(dto.getModel());
        e.setParameters(dto.getParameters());
        e.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
        e.setIsDefault(dto.getIsDefault() == null ? 0 : dto.getIsDefault());
        e.setRemark(dto.getRemark());
        LLMModelEntity saved = modelService.createOrUpdate(e);
        // mask api key in response
        saved.setApiKey(mask(saved.getApiKey()));
        return PAIResponseBeanUtil.success(saved);
    }

    @DeleteMapping("/{id}")
    @OperationLog(module = "AIGC管理", operation = "LLM模型删除", description = "管理员删除LLM模型", recordParams = false)
    public PAIResponseBean<Boolean> delete(@PathVariable("id") Long id) {
        modelService.delete(id);
        return PAIResponseBeanUtil.success(true);
    }

    @GetMapping("/list")
    public PAIResponseBean<List<LLMModelEntity>> list(@RequestParam String tenantId) {
        List<LLMModelEntity> list = modelService.listEnabledModels(tenantId)
                .stream().peek(m -> m.setApiKey(mask(m.getApiKey())))
                .collect(Collectors.toList());
        return PAIResponseBeanUtil.success(list);
    }

    @PostMapping("/icon/upload")
    @OperationLog(module = "AIGC管理", operation = "LLM模型图标上传", description = "上传模型图标到OSS", recordParams = false)
    public PAIResponseBean<String> uploadIcon(@RequestPart("file") MultipartFile file) {
        PAIResponseBean<UploadResultVO> resp = fileServiceClient.upload(file);
        if (!resp.getSuccess() || resp.getData() == null) {
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"图标上传失败");
        }
        return PAIResponseBeanUtil.success(resp.getData().getUrl());
    }

    private String mask(String s) {
        if (s == null || s.length() <= 8) return "********";
        return s.substring(0, 4) + "****" + s.substring(s.length() - 4);
    }
}
